// Ofri Keidar 302933981 group 05

package operator;

import java.io.IOException;

import model.ApartmentsManager;
import model.Model;
import model.database.ApartmentsDB;
import model.database.DBException;
import model.database.Database;
import controller.DBController;
import controller.Transactor;
import server.ServerController;

/**
 * This class holds main function, where server's system is initialized and then starts running 
 */
public class OperateServer {

	private ServerController server; // server object

	/**
	 * Creates a new OperateServer instance and initializes system
	 * @throws DBException if had problems creating components involving the database-system
	 * @throws IOException if had problems creating the server controller
	 */
	public OperateServer() throws DBException, IOException {
		
		// create a new database
		Database database = new ApartmentsDB();

		// create a new model
		Model model = new ApartmentsManager(database);

		// create a controller
		DBController controller = new Transactor(model);
		
		// create a new server
		server = new ServerController(controller);
	}
	
	/**
	 * Creates a new OperateServer object, initializes system and starts server's running
	 * @param args- none
	 */
	public static void main(String[] args) {

		// allocate a new operator for the system
		OperateServer operator = null;
		try {
			
			operator = new OperateServer();
			operator.start(); // run server
			
		} catch (DBException e) {
			
			// display error message
			System.out.println(e.getMessage());
			
		} catch (IOException e) {

			// display error message
			System.out.println(e.getMessage());
			
		} finally {
			try {
				
				// check if could create operator
				if (operator == null) {
					
					// cannot close server
					return;
				}
				
				// close server
				System.out.println("Closing server...");
				operator.shutDown();
				System.out.println("New clients are not allowed to connect. Server will be closed after last client is done");
				
			} catch (IOException e) {			
				e.printStackTrace();
			}
		}
	}

	/**
	 * Starts server's running using the server controller object
	 * @throws IOException if had problems communicating with client 
	 */
	private void start() throws IOException {
		
		// start server's running
		server.listenToClients();
	}
	
	/**
	 * Closes server
	 * @return True if could close server, False if not
	 * @throws IOException if had problems closing server
	 */
	private boolean shutDown() throws IOException {
		
		// check if could create server
		if (server == null) {
			
			// could not close server
			return false;
		}
		
		// close server
		return server.closeServerSocket();
	}
}
